#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "parallel_for.h"

static void* parallel_for_worker(void *arg) {
    parallel_for_args *p_args = (parallel_for_args*)arg;
    for(int i = p_args->start; i < p_args->end; i += p_args->inc) {
        p_args->func(i, p_args->args);
    }
    return NULL;
}

void parallel_for(int start, int end, int inc, void *(*func)(int, void*), void *args, int num_threads) {
    pthread_t *threads = malloc(num_threads * sizeof(pthread_t));
    parallel_for_args *thread_args = malloc(num_threads * sizeof(parallel_for_args));
    
    // 计算每个线程的工作量
    int total_iterations = (end - start) / inc;
    int iterations_per_thread = total_iterations / num_threads;
    int remainder = total_iterations % num_threads;
    
    int current_start = start;
    for(int i = 0; i < num_threads; i++) {
        int iterations = iterations_per_thread + (i < remainder ? 1 : 0);
        thread_args[i].start = current_start;
        thread_args[i].end = current_start + iterations * inc;
        thread_args[i].inc = inc;
        thread_args[i].func = func;
        thread_args[i].args = args;
        
        pthread_create(&threads[i], NULL, parallel_for_worker, &thread_args[i]);
        
        current_start = thread_args[i].end;
    }
    
    // 等待所有线程完成
    for(int i = 0; i < num_threads; i++) {
        pthread_join(threads[i], NULL);
    }
    
    free(threads);
    free(thread_args);
}